import React, { useState, useEffect, useRef } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { Menu, Form, Button, Dropdown, message, Card, Input, Tabs, Modal } from 'antd';
import styles from './style.less';
import { FormComponentProps } from 'antd/lib/form';
import { bdExec } from '@/helpers/RequestHelper';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { DownOutlined, PlusCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { FormValueType } from './components/ConfigForm';
import ConfigForm from './components/ConfigForm';
import DataForm from './components/DataForm';
import { addRule, updateRule, removeRule, queryRule, queryListRule } from './service';
import * as tsxHelper from '@/helpers/TsxHelper';
import PreviewForm from '@/components/PreviewForm';
import * as DataHelper from '@/helpers/DataHelper';
const { Item } = Menu;
const { TabPane } = Tabs;
interface ConfigListProps extends FormComponentProps {
    dataImgModalVisible: boolean;
    onSubmit: (fieldsValue: any) => any;
    onCancel: () => void;
}

const handleAdd = async (fields: FormValueType) => {
    return bdExec({ fn: addRule, args: fields, successMsg: '添加成功', failMsg: '添加失败请重试！' });
};

const handleUpdate = async (fields: FormValueType) => {
    return bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};

const handleRemove = async (selectedRows: any[]) => {
    if (!selectedRows) return true;
    const ids: any = selectedRows.map(row => row.id).toString();
    return bdExec({ fn: removeRule, args: { ids }, successMsg: '删除成功，即将刷新', failMsg: '删除失败，请重试！', hasLoading: false });
};

const ConfigList: React.FC<ConfigListProps> = props => {
    const { form, dataImgModalVisible, onSubmit: handleSubmitImg, onCancel,
    } = props;
    let main: HTMLDivElement | undefined | any = undefined;
    const actionRef = useRef<ActionType>();
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const [selectIndex, setSelectIndex] = useState<string>('');
    const [groupId, setgroupId] = useState<string>('');
    const [mode, setMode] = useState<any>('inline');
    const [rowKeys, setRowKeys] = useState<string[] | number[]>([]);
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    const [radioType, setRadioType] = useState<string | 'string' | 'switch' | 'date' | 'file' | 'color'>('string');
    const [picture, setPicture] = useState<any[]>([]);
    const [color, setColor] = useState<string>('#1890ff');
    const [stateData, setStateData] = useState<any>({ common: {} });
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    const [selectImg, setSelectImg] = useState('');
    const [radioType1, setRadioType1] = useState<any>()
    const [all, setAll] = useState<any>();
    // 表单可见 关键变量
    const handleChange = (value: any) => {
        setRadioType1(value)
    }
    const [keyWord, setKeyWord] = useState<string>();
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    useEffect(() => {
        window.addEventListener('resize', resize);
        resize();
        initData();
        return () => window.removeEventListener('resize', resize);
    }, []);

    const columns: ProColumns<any>[] = [
        {
            title: 'ID',
            dataIndex: 'id',
        },
        {
            title: '名称',
            dataIndex: 'name',
            width: 200
        },
        {
            title: '图片',
            dataIndex: 'oss_url',
            hideInSearch: true,
            render: (value, record) => (
                <img src={record.oss_url} width='80px' onClick={() => {
                    setPreviewImg(record.oss_url)
                    handlePreviewModalVisible(true)
                }} />
            )
        },
        {
            title: '大小',
            dataIndex: 'file_size',
            hideInSearch: true,
        },
        {
            title: '排序',
            dataIndex: 'rank_num',
            hideInSearch: true,
        },
        {
            title: '上传时间',
            dataIndex: 'created_at',
            sorter: true,
            hideInSearch: true,
        },
    ];

    const initData = (isTrue?:any) => {
        const args: any = {};
        console.log('....1111')
        // window.location.pathname.split('/').map((v: any) => {
        //     if (v.indexOf('type_') > -1) {
        //         console.log('....')
        //         args.type = v.split('type_')[1]
        //     }
        // })

        args.type = 'source';
        // args.config_group_id = 5
        return bdExec({
            fn: queryRule,
            args,
            failMsg: '请求数据失败',
            hasCallBack: true,
            hasLoading: false,
        }).then((res: any) => {
            if (res.execStatus) {
                // todo 注意： 如果state为一个对象时，这个时候需要进行合并的。 
                setStateData(res.data)
                setgroupId(res.data.data[0].config_group_id)
                if(!isTrue){
                    setSelectIndex(res.data.data[0].id.toString());
                    setRadioType1(res.data.data[0].id.toString())
                }
                setAll(res.data.data[0].id.toString());
                console.log(12, res.data.data[0].id)
                // params && setSelectIndex(params.selectIndex == '' ?
                //     res.data.common.sideBarList[0].id.toString() : params.selectIndex);
                return res.data.listData;
            }
        })
    }
    const initListData = (params?: any) => {
        const args: any = {};
        args.nickname = 'source_pic';
        params && params.selectIndex != ''  &&  params.selectIndex != all && (args.group_id = Number(params.selectIndex));
        params && params.name && (args.name = params.name);
        params && params.id && (args.id = params.id);
        return bdExec({
            fn: queryListRule,
            args,
            failMsg: '请求数据失败',
            hasCallBack: true,
            hasLoading: false,
        }).then((res: any) => {
            if (res.execStatus) {
                return res.data.listData;
            }
        })
    }

    const initValuesData = (record: any) => {
        setIsUpdate(true);
        setStepFormValues(record);
        setRadioType(record.type);
        record.type == 'color' && setColor(record.content);
        record.type == 'file' && buildPicture(record.content);
    }

    const getMenu = () => {
        const menuMap = stateData.data || [];
        return menuMap.map((item: any) => <Item key={`${item.id}`}>{item.name}（{item.count}）</Item>);
    };

    const getRightTitle = () => {
        const menuMap = stateData.data || [];
        const selectItem = menuMap.filter((item: any) => item.id.toString() === selectIndex);
        return selectItem.length > 0 ? selectItem[0].name : '';
    };

    const selectKey = (key: string) => {
        setSelectIndex(key);
        setRadioType1(key);
        // if (actionRef.current) {
        //   actionRef.current.reload();
        // }
    };

    const resize = () => {
        if (!main) {
            return;
        }
        requestAnimationFrame(() => {
            if (!main) {
                return;
            }
            let mode: 'inline' | 'horizontal' = 'inline';
            const { offsetWidth } = main;
            if (main.offsetWidth < 641 && offsetWidth > 400) {
                mode = 'horizontal';
            }
            if (window.innerWidth < 768 && offsetWidth > 400) {
                mode = 'horizontal';
            }
            setMode(mode);
        });
    };
    const buildPicture = (url: any) => {
        if (url) {
            setPicture([{
                uid: '-1',
                name: url.split('/').pop(),
                status: 'done',
                url: url,
                thumbUrl: url,
            }]);
        }
    }

    const handleOnSubmit = (value: FormValueType) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then(status => {
            if (status) {
                handleModalVisible(false);
                setPicture([]);
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            return status; // 返回执行结果:boolean, 子组件接收此值来判断是否重置表单数据
        })
    }
    // 表单提交
    const handleSubmitDataForm = (value: any) => {
        return new Promise((resolve, reject) => {
            let s = isUpdate ? handleUpdate(value) : handleAdd(value);
            resolve(s);
        }).then(status => {
            console.log("handleSubmitDataForm status is ", status)
            if (status) {
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                initData(true);
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }
    const handleSetPicture = (value: any) => {
        setPicture(value)
    }
    const handleSubmit = async (fieldsValue:any) => {
        setPicture([])
        handleModalVisible(false)
        await initData(true);
        if (actionRef.current) {
            actionRef.current.reload();
        }
        // handleSubmitImg(fieldsValue)
    }
    const handleDetail = () => {
        window.open(
            `${window.location.origin}/miniAppdeploy/material`,
            '_blank',
        );
    };
    const okHandle = async () => {
        if(selectImg == ''){
            message.error('请选择图片');
            return;
        }
        setPicture([])
        handleModalVisible(false)
        await initData(true);
        if (actionRef.current) {
            actionRef.current.reload();
        }
        handleSubmitImg(selectImg)
        //handleSubmit(selectImg);
    };
    // console.log('update-->selectIndex-->', selectIndex)
    return (
        <Modal
            destroyOnClose
            title={'选择图片'}
            width={DataHelper.DEFAULT_MODAL_WIDTH}
            visible={dataImgModalVisible}
            onOk={okHandle}
            onCancel={() => onCancel()}
        >
            <GridContent>
                <div
                    className={styles.mainImg}
                    ref={ref => {
                        if (ref) {
                            main = ref;
                        }
                    }}
                >
                    <div className={styles.leftMenu}>
                        {groupId != '' ?
                            <Menu
                                mode={mode}
                                selectedKeys={[selectIndex]}
                                onClick={({ key }) => selectKey(key)}
                            >
                                {getMenu()}
                            </Menu>
                            : null}
                    </div>
                    {groupId != '' ?
                        <div className={styles.right}>
                            <ProTable<any>
                                // headerTitle={getRightTitle()}
                                actionRef={actionRef}
                                rowKey="key"
                                search={false}
                                pagination={{
                                    showSizeChanger: true,
                                }}
                                options={false}
                                toolBarRender={(action, { selectedRows }) => [
                                    <Input.Search placeholder="图片名称" onSearch={(value) => {
                                        setKeyWord(value)
                                    }} />,
                                    <Button icon={'plus'}
                                        onClick={() => {
                                            handleModalVisible(true)
                                            setIsUpdate(false);
                                        }}
                                    >
                                        上传图片
                                    </Button>,
                                    <Button
                                        type="primary"
                                        onClick={() => {
                                            handleDetail();
                                        }}
                                        style={{ marginRight: '-8px' }}
                                    >
                                        前往素材中心
                                </Button>
                                ]}
                                tableAlertRender={false}
                                request={(params) => initListData(params)}
                                // 这个参数会自动注入到params中去，如果selectIndex修改， 还会触发reload()
                                params={{
                                    selectIndex,
                                    name: keyWord
                                }}
                                columns={columns}
                                rowSelection={{
                                    type:'radio',
                                    onChange: (selectedRowKeys, selectedRows) => {
                                        setRowKeys(selectedRowKeys);
                                        setSelectImg(selectedRows);
                                    },
                                    selectedRowKeys: rowKeys,
                                }}
                            />
                            <ConfigForm
                                onCancel={() => {
                                    handleModalVisible(false);
                                    setPicture([]);
                                }}
                                onSubmit={handleSubmit}
                                dataModalVisible={createModalVisible}
                                dataFormValues={ }
                                picture={picture}
                                handleSetPicture={handleSetPicture}
                                radioType1={radioType1}
                                handleChange={handleChange}
                                allGroup={all}
                                common={stateData.data.filter((item: any, index: any) => index != 0)}
                                isUpdate={false}

                            />
                            {
                                previewModelVisible && (
                                    <PreviewForm
                                        previewModelVisible={previewModelVisible}
                                        onVisibleModel={handlePreviewModalVisible}
                                        previewImg={previewImg}
                                    />
                                )
                            }
                        </div>
                        : null}
                </div>
            </GridContent>
            <DataForm
                dataModalVisible={dataModalVisible}
                dataFormValues={dataFormValues}
                isUpdate={isUpdate}
                onSubmit={async formValue => handleSubmitDataForm(formValue)}
                onCancel={() => handleDataModalVisible(false)}
            />
        </Modal>
    );
}

export default Form.create<ConfigListProps>()(ConfigList);

